package com.ruoyi.produce.process.planself.service;


import com.ruoyi.DingDing.Domain.DingDingText;
import com.ruoyi.constant.ERPConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.personnel.oa.approve.domain.ApproveDomain;
import com.ruoyi.personnel.oa.approve.mapper.ApproveMapper;
import com.ruoyi.personnel.oa.sequence.service.IApproveSequenceService;
import com.ruoyi.produce.base.offer.domain.ProduceOfferDomain;
import com.ruoyi.produce.base.offer.domain.ProduceOfferListDomain;
import com.ruoyi.produce.base.offer.service.IProduceOfferService;
import com.ruoyi.produce.process.planoutsource.domain.ProducePlanOutsource;
import com.ruoyi.produce.process.planoutsource.service.IProducePlanOutsourceService;
import com.ruoyi.produce.process.planself.domain.ProducePlanMonthlyProduction;
import com.ruoyi.produce.process.planself.domain.ProducePlanSelfCond;
import com.ruoyi.produce.process.planself.domain.ProducePlanSelfDomain;
import com.ruoyi.produce.process.planself.domain.ProducePlanSelfDto;
import com.ruoyi.produce.process.planself.mapper.ProducePlanSelfMapper;
import com.ruoyi.produce.process.worksheet.domain.ProduceWorkSheet;
import com.ruoyi.produce.process.worksheet.mapper.ProduceWorkSheetMapper;
import com.ruoyi.produce.report.produceAnalysis.domain.ProduceAnalysis;
import com.ruoyi.psi.base.cost.domain.ProductionCostListDto;
import com.ruoyi.psi.base.cost.service.IProductionCostService;
import com.ruoyi.utils.ID.IdUtil;
import com.ruoyi.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import java.sql.Timestamp;
import java.util.*;

/**
 * 自产生产计划
 * 业务执行层
 */
@Service
public class ProducePlanSelfServiceImpl implements IProducePlanSelfService {
    @Autowired
    private ProducePlanSelfMapper producePlanSelfMapper;
    @Autowired
    private IProduceOfferService produceOfferService; //生产报价
    @Autowired
    private IProductionCostService productionCostService; //商品成本
    @Autowired
    private ProduceWorkSheetMapper produceWorkSheetMapper;
    @Autowired
    private IdUtil idUtil;
    @Autowired
    private IApproveSequenceService approveSequenceService;
    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private IProducePlanOutsourceService producePlanOutsourceService;

    /**
     * 查找成品自产生产计划
     *
     * @param cond
     * @return
     */
    @Override
    public List<ProducePlanSelfDto> selectProducePlanSelfListByFinished(ProducePlanSelfCond cond) {
        List<ProducePlanSelfDto> producePlanSelfDtos = producePlanSelfMapper.selectProducePlanSelfListByFinished(cond);
        System.out.println("cond------"  +cond);
        String planSelfIdCond = cond.getPlanSelfId(); //查询条件
        //将每个成品计划对应的半成品计划都存放入成品计划内
        if (planSelfIdCond != null && !planSelfIdCond.equals("")) {
            // 有查询条件
            ProducePlanSelfDto producePlanSelfDto = producePlanSelfMapper.selectProducePlanSelfById(planSelfIdCond);
            List<ProducePlanSelfDto> resList = new ArrayList<>();
            resList.add(producePlanSelfDto);
            return resList;
        }
        for (int i = 0; i < producePlanSelfDtos.size(); i++) {
            if (producePlanSelfDtos.get(i).getPlanSelfNumber() != 0.000) {
                // 设置计划状态，完成数/计划数的百分比
                producePlanSelfDtos.get(i).setPlanSelfStatus(
                        (BigDecimal.valueOf(producePlanSelfDtos.get(i).getCompletedNumber())
                                .divide(BigDecimal.valueOf(producePlanSelfDtos.get(i).getPlanSelfNumber()), 2, BigDecimal.ROUND_HALF_UP)
                                .multiply(BigDecimal.valueOf(100)))
                                + "%"
                );
            }

            producePlanSelfDtos.get(i).setUnfinishedQuantity(producePlanSelfDtos.get(i).getPlanSelfNumber() - producePlanSelfDtos.get(i).getCompletedNumber());
            String planSelfIdParent = producePlanSelfDtos.get(i).getPlanSelfId();
            producePlanSelfDtos.get(i).setProducePlanSelves(producePlanSelfMapper.selectProducePlanSelfByUnfinishedList(planSelfIdParent));
        }
        return producePlanSelfDtos;
    }

    /**
     * 查找未完成成品自产生产计划
     * @param cond
     * @return
     */
    @Override
    public List<ProducePlanSelfDto> selectProcessingProducePlanSelfListByFinished(ProducePlanSelfCond cond) {
        List<ProducePlanSelfDto> producePlanSelfDtos = producePlanSelfMapper.selectProcessingProducePlanSelfListByFinished(cond);
        //将每个成品计划对应的半成品计划都存放入成品计划内
        for (int i = 0; i < producePlanSelfDtos.size(); i++) {

            if (producePlanSelfDtos.get(i).getPlanSelfNumber() != 0.000) {
                // 设置计划状态，完成数/计划数的百分比
                producePlanSelfDtos.get(i).setPlanSelfStatus(
                        (BigDecimal.valueOf(producePlanSelfDtos.get(i).getCompletedNumber())
                                .divide(BigDecimal.valueOf(producePlanSelfDtos.get(i).getPlanSelfNumber()), 2, BigDecimal.ROUND_HALF_UP)
                                .multiply(BigDecimal.valueOf(100)))
                                + "%"
                );
            }

            producePlanSelfDtos.get(i).setUnfinishedQuantity(producePlanSelfDtos.get(i).getPlanSelfNumber() - producePlanSelfDtos.get(i).getCompletedNumber());
            String planSelfIdParent = producePlanSelfDtos.get(i).getPlanSelfId();
            producePlanSelfDtos.get(i).setProducePlanSelves(producePlanSelfMapper.selectProducePlanSelfByUnfinishedList(planSelfIdParent));
        }
        return producePlanSelfDtos;
    }

    /**
     * 根据编号查找自产生产计划
     *
     * @param planSelfId 自产生产计划编号
     * @return
     */
    @Override
    public ProducePlanSelfDto selectProducePlanSelfById(String planSelfId) {
        ProducePlanSelfDto producePlanSelf = producePlanSelfMapper.selectProducePlanSelfById(planSelfId);
        if (!producePlanSelf.getCompletionStatus().equals(ERPConstant.COMMON_FINISHED)) {
            //未完成
            // 设置计划状态，完成数/计划数的百分比
            if (producePlanSelf.getPlanSelfNumber() != 0.000) {
                producePlanSelf.setPlanSelfStatus(
                        (BigDecimal.valueOf(producePlanSelf.getCompletedNumber())
                                .divide(BigDecimal.valueOf(producePlanSelf.getPlanSelfNumber()), 2, BigDecimal.ROUND_HALF_UP)
                                .multiply(BigDecimal.valueOf(100)))
                                + "%"
                );
            }
        }
        producePlanSelf.setUnfinishedQuantity(producePlanSelf.getPlanSelfNumber() - producePlanSelf.getCompletedNumber());
        String planSelfIdParent = producePlanSelf.getPlanSelfId();
        producePlanSelf.setProducePlanSelves(producePlanSelfMapper.selectProducePlanSelfByUnfinishedList(planSelfIdParent));
        return producePlanSelf;
    }

    /**
     * 新增自产生产计划
     *
     * @param producePlanSelf
     * @return
     */
    @Override
    public int insertProducePlanSelf(ProducePlanSelfDomain producePlanSelf) throws Exception {
        String producePlanSelfId = idUtil.createProducePlanSelfId();//自动生成编号
        if (StringUtils.isNotNull(producePlanSelfMapper.selectProducePlanSelfById(producePlanSelfId))) {
            //存在
            return 0;
        }
        producePlanSelf.setPlanSelfId(producePlanSelfId);
        ApproveDomain approve = new ApproveDomain(producePlanSelfId, "生产计划审批", ERPConstant.APPROVAL_TYPE_PRODUCE_PLAN); //新增审批
        approve.setCurrentApprover(approveSequenceService.getLowestRoleId(ERPConstant.APPROVAL_TYPE_PRODUCE_PLAN));
        approveMapper.insertApprove(approve);
        Long currentApprover = approve.getCurrentApprover();
        DingDingText dingDingText = new DingDingText();
        dingDingText.BatchRobotText(currentApprover);
        return producePlanSelfMapper.insertProducePlanSelf(producePlanSelf);
    }

    /**
     * 更新自产生产计划
     *
     * @param producePlanSelf
     * @return
     */
    @Override
    public int updateProducePlanSelf(ProducePlanSelfDomain producePlanSelf) {
        if (!StringUtils.isNotNull(producePlanSelfMapper.selectProducePlanSelfById(producePlanSelf.getPlanSelfId()))) {
            //存在
            return 0;
        }
        return producePlanSelfMapper.updateProducePlanSelf(producePlanSelf);
    }

    /**
     * 删除自产生产计划
     * 仅修改删除标志
     *
     * @param producePlanSelf
     * @return
     */
    @Override
    public int updateProducePlanSelfDeleteFlag(ProducePlanSelfDomain producePlanSelf) {
        return producePlanSelfMapper.updateProducePlanSelfDeleteFlag(producePlanSelf);
    }

    /**
     * 获取当前编号最大的生产计划
     *
     * @return
     */
    @Override
    public String selectMaxProducePlanSelfId() {
        return producePlanSelfMapper.selectMaxProducePlanSelfId();
    }

    /**
     * 根据生产计划自动批量生成生产报价
     *
     * @return
     */
    @Override
    public int releaseProduceOffer(String[] args) {
        for (int i = 0; i < args.length; i++) {
            ProduceOfferDomain produceOffer = new ProduceOfferDomain();
            List<ProduceOfferListDomain> produceOfferListDomainList = new ArrayList<>(); //创建一个子表的集合
            // 主表：生成最新的一条生产报价编号
            String produceOfferId = idUtil.createProduceOfferId();
            produceOffer.setProduceOfferId(produceOfferId);
            // 主表：生成关联编号
            produceOffer.setAssociationId(args[i]);
            // 根据传入的生产计划编号获取相应的记录
            ProducePlanSelfDto producePlanSelf = producePlanSelfMapper.selectProducePlanSelfById(args[i]);
            // 主表：获取报价产品
            produceOffer.setProduceId(producePlanSelf.getProduceId());
            // 主表：获取计划报价数量
            produceOffer.setOfferNumber(producePlanSelf.getPlanSelfNumber());
            // 主表：生成报价日期
            Timestamp date = new Timestamp(new Date().getTime());
            produceOffer.setCreateTime(date);
            // 主表：生成备注
            produceOffer.setRemark("由生产计划" + args[i] + "生成的生产报价");
            // 添加子表
            List<ProductionCostListDto> productionCostListDtoList = productionCostService.selectProductionCostListListById(producePlanSelf.getProduceId());
            for (int j = 0; j < productionCostListDtoList.size(); j++) {
                // 创建一个子表对象并且赋值
                ProduceOfferListDomain produceOfferListDomain = new ProduceOfferListDomain();
                produceOfferListDomain.setProduceOfferId(produceOfferId);
                produceOfferListDomain.setCostItemId(productionCostListDtoList.get(j).getCostItemId());
                produceOfferListDomain.setCostUnitPrice(productionCostListDtoList.get(j).getCostUnitPrice());
                produceOfferListDomain.setCostNumber(productionCostListDtoList.get(j).getCostNumber());

                produceOfferListDomainList.add(produceOfferListDomain);
//            System.out.println("当前新增的子表对象" + produceOfferListDomain);
            }
            produceOffer.setOfferListDomainList(produceOfferListDomainList);
//        System.out.println("循环结束最终的子表" + produceOfferListDomainList);
            try {
                // 新增生产报价记录
                produceOfferService.insertProduceOffer(produceOffer);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
        return 1;
    }

    /**
     * 生产计划加工单下达
     * @param workSheet
     * @return
     */
    @Override
    public int releaseWorksheet(ProduceWorkSheet workSheet) {
        ProduceWorkSheet produceWorkSheet = new ProduceWorkSheet();
        String workSheetId = idUtil.createWorkSheetId();
        produceWorkSheet.setWorkSheetId(workSheetId);
        produceWorkSheet.setPlanSelfId(workSheet.getPlanSelfId()); //关联生产计划编号
        ProducePlanSelfDto producePlanSelf = producePlanSelfMapper.selectProducePlanSelfById(workSheet.getPlanSelfId());//根据生产计划编号获取对应的生产计划信息
        // 产品数据
        produceWorkSheet.setProduceId(producePlanSelf.getProduceId());
        produceWorkSheet.setProduceName(producePlanSelf.getProduceName());
        produceWorkSheet.setBaseCategoryId(producePlanSelf.getBaseCategoryId());
        produceWorkSheet.setBaseCategoryName(producePlanSelf.getBaseCategoryName());
        produceWorkSheet.setBaseUnitId(producePlanSelf.getBaseUnitId());
        produceWorkSheet.setBaseUnit(producePlanSelf.getBaseUnit());
        produceWorkSheet.setProduceSpecs(producePlanSelf.getProduceSpecs());
        produceWorkSheet.setWorkSheetNumber(workSheet.getWorkSheetNumber()); //计划数量
        produceWorkSheet.setStartTime(workSheet.getStartTime()); //开始时间
        produceWorkSheet.setPredictedFinishingTime(workSheet.getPredictedFinishingTime()); //预计完成时间
        produceWorkSheet.setCreateById(workSheet.getCreateById()); //创建人
        produceWorkSheet.setRemark(workSheet.getRemark()); //备注
        try {
            ApproveDomain approve = new ApproveDomain(workSheetId, "加工单审批", ERPConstant.APPROVAL_TYPE_WORKSHEET, produceWorkSheet.getCreateById()); //新增审批
            approve.setCurrentApprover(approveSequenceService.getLowestRoleId(ERPConstant.APPROVAL_TYPE_WORKSHEET));
            approveMapper.insertApprove(approve);
            produceWorkSheetMapper.insertProduceWorkSheet(produceWorkSheet);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    /**
     * 生产计划下达委外加工单
     * @param planOutsource
     * @return
     */
    @Override
    public int releaseProducePlanOutsource(ProducePlanOutsource planOutsource) {
        ProducePlanOutsource producePlanOutsource = new ProducePlanOutsource();
        producePlanOutsource.setPlanSelfId(planOutsource.getPlanSelfId()); //关联生产计划编号
        producePlanOutsource.setPlanOutsourceNumber(planOutsource.getPlanOutsourceNumber()); // 计划数量
        producePlanOutsource.setSupplierInfoId(planOutsource.getSupplierInfoId()); //供应商
        producePlanOutsource.setPlanOutsourceUnitPrice(planOutsource.getPlanOutsourceUnitPrice());  //单价
        producePlanOutsource.setMaterialMarks(planOutsource.getMaterialMarks()); //是否提供材料
        producePlanOutsource.setStartTime(planOutsource.getStartTime()); //开始时间
        producePlanOutsource.setPredictedFinishingTime(planOutsource.getPredictedFinishingTime()); //预计完成时间
        producePlanOutsource.setRemark(planOutsource.getRemark()); //备注
        try {
            producePlanOutsourceService.insertProducePlanOutsource(producePlanOutsource);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    /**
     * 查询月销售产量
     * @return
     */
    @Override
    public List<ProducePlanMonthlyProduction> searchMonthlyProduction() {
        List<ProducePlanMonthlyProduction> producePlanMonthlyProductions = producePlanSelfMapper.searchMonthlyProduction();

        //月份去重
        Map<String, ProducePlanSelfDto> monthMap = new LinkedHashMap<>();
        for (ProducePlanMonthlyProduction item : producePlanMonthlyProductions) {
            ProducePlanSelfDto producePlanSelf = producePlanSelfMapper.selectProducePlanSelfById(item.getPlanSelfId());
            if (!monthMap.containsKey(item.getMont())) {
                monthMap.put(item.getMont(), producePlanSelf);
            } else {
                ProducePlanSelfDto producePlanSelfDto = monthMap.get(item.getMont());
                producePlanSelfDto.setPlanSelfNumber(producePlanSelfDto.getPlanSelfNumber() + producePlanSelf.getPlanSelfNumber());
                producePlanSelfDto.setCompletedNumber(producePlanSelfDto.getCompletedNumber() + producePlanSelf.getCompletedNumber());
            }
        }
        List<ProducePlanMonthlyProduction> resultList = new ArrayList<>(); //返回类
        for (Map.Entry<String, ProducePlanSelfDto> entry : monthMap.entrySet()) {
            ProducePlanMonthlyProduction producePlanMonthlyProduction = new ProducePlanMonthlyProduction();
            producePlanMonthlyProduction.setMont(entry.getKey());
            producePlanMonthlyProduction.setPlanSelfNumber(entry.getValue().getPlanSelfNumber());
            producePlanMonthlyProduction.setCompletedNumber(entry.getValue().getCompletedNumber());
            resultList.add(producePlanMonthlyProduction);
        }
        return resultList;
    }

    /**
     * 查询销售订单进度
     *
     * @param saleOrderId
     * @return
     */
    @Override
    public List<ProduceAnalysis> searchSaleOrderProgress(String saleOrderId) {
        List<ProduceAnalysis> produceAnalysisList = new ArrayList<>();
        List<ProducePlanSelfDto> producePlanSelfDtos = producePlanSelfMapper.selectProducePlanSelfBySaleOrderId(saleOrderId);
        for (ProducePlanSelfDto item : producePlanSelfDtos) {
            ProduceAnalysis produceAnalysis = new ProduceAnalysis(
                    item.getPlanSelfId(),
                    item.getProduceId(),
                    item.getProduceName(),
                    item.getBaseCategoryId(),
                    item.getBaseCategoryName(),
                    item.getBaseUnitId(),
                    item.getBaseUnit(),
                    item.getProduceSpecs(),
                    item.getProduceBrand(),
                    item.getCompletionStatus(),
                    item.getPlanSelfNumber(),
                    item.getCompletedNumber()
            );
            produceAnalysis.setStartTime(item.getStartTime());
            produceAnalysis.setPredictedFinishingTime(item.getPredictedFinishingTime());
            produceAnalysis.setEndTime(item.getEndTime());
            if (item.getStartTime() != null && item.getPredictedFinishingTime() != null) {
                if (item.getEndTime() != null) {
                    produceAnalysis.setProductionTime(TimeUtil.TimeSubtraction(item.getEndTime(), item.getStartTime()) + 1);
                    long time = TimeUtil.TimeSubtraction(item.getPredictedFinishingTime(), item.getEndTime());
                    if (time >= 0) {
                        time += 1;
                    } else {
                        time -= 1;
                    }
                    produceAnalysis.setAdvanceTime(time);
                } else {
                    // 未完成
                    produceAnalysis.setProductionTime(999999999);
                    produceAnalysis.setAdvanceTime(999999999);
                }
            } else {
                // 未完成
                produceAnalysis.setProductionTime(999999999);
                produceAnalysis.setAdvanceTime(999999999);
            }
            produceAnalysisList.add(produceAnalysis);
        }
        return produceAnalysisList;
    }
}
